<template>
  <div class="main-box">
    <div class="chat-chat">
      <chat ref="chatRef" :info-data="data" :load="aiMecssageLoad" @newInfoChange="newInfoChange"
        style="height: calc(100vh - 100px);"></chat>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import chat from "@/components/Chat/index.vue"
const data = reactive([])

const chatRef = ref(null);
const aiMecssageLoad = ref(false);
const newInfoChange = info => {
  aiMecssageLoad.value = true;
  callChatGPT(info.value).then(res => {
    chatRef.value.addInfo({
      value: res
    })
  }).catch(err => {
    chatRef.value.addInfo({
      value: err
    })
  }).finally(() => {
    aiMecssageLoad.value = false;
  })
}

// const response = ref('')
const selectedCities = ref([])
const selectedDays = ref([])

const cities = computed(() => selectedCities.value.map((city) => city[1]))
console.log(cities)
const days = computed(() => selectedDays.value.map((day) => day[0]))
console.log(days)

const callChatGPT = (message) => {
  return new Promise((resolve, reject) => {
    const API_KEY = "sk-proj-MiHTUCFAWOEz928O5McPT3BlbkFJWHBJWry3vrBUkmCg3g8S"
    const url = 'https://api.openai.com/v1/chat/completions'
    // const url = "https://api.openai.com/v1/engine/davinci/completions";
    const requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${API_KEY}`,
        auth: `Bearer ${API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: message }],
        temperature: 0.7
      })
    }
    try {
      fetch(url, requestOptions).then(response => {
        response.json().then(data => {
          console.log(data)
          if (data.choices && data.choices.length > 0) {
            const message = data.choices[0].message.content
            resolve(message)
          } else {
            reject("Error: Unexpected API response format");
          }
        }).catch(error => {
          reject(error.message);
        });
      })
    } catch (error) {
      reject(error.message);
    }
  })

}
</script>
<style lang="scss">
.main-box {
  background-color: #111;
  margin-top: 100px;
}

.chat-chat {
  width: 1200px;
  background-color: #191919;
  margin: auto;
}
</style>